package com.demo.producer;

import com.alibaba.fastjson.JSON;
import com.demo.common.Constant;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.nio.charset.StandardCharsets;

/**
 * 延时消息:用于类似点餐,点击支付,但是却未支付并取消了,而一段时间内,库存不会立马释放,过了一段时间后检查才做业务
 *
 * @author yexi
 */
public class DelayProducer {
    public static void main(String[] args) throws MQClientException, RemotingException, InterruptedException, MQBrokerException {
        DefaultMQProducer defaultMQProducer = new DefaultMQProducer(Constant.PRODUCER_GROUP_1);
        defaultMQProducer.setNamesrvAddr(Constant.ROCKET_MQ_ADDRESS);
        defaultMQProducer.start();
        String topic = "04-delay";
        String tags = "tagA";
        String msg = "RocketMQ Delay Send ";
        for (int i = 0; i < 100; i++) {
            Message message = new Message(
                    topic,
                    tags,
                    (msg + i).getBytes(StandardCharsets.UTF_8)
            );
            //设置延迟级别,每种级别代表不同时间
            message.setDelayTimeLevel(2);
            SendResult sendResult = defaultMQProducer.send(message);
            System.out.println("发送后返回的消息: " + JSON.toJSONString(sendResult));
            System.out.println("成功发送的消息ID: " + sendResult.getMsgId());
            System.out.println("----------------------------");
        }
        defaultMQProducer.shutdown();
    }
}
